package com.card.server.controller;


import com.card.server.domain.R;
import com.card.server.model.dto.SignDto;
import com.card.server.model.entity.Users;
import com.card.server.model.ro.UserInfo;
import com.card.server.service.IUserService;
import com.card.server.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {

    private static final Logger log = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private IUserService userService;

    @PostMapping("/register")
    public R<Users> register(@RequestBody SignDto signDto) {
        log.info("用户名称:{},用户密码:{}", signDto.getAccount(), signDto.getPassword());
        return userService.register(signDto);
    }

    @PostMapping("/login")
    public R<String> login(@RequestBody SignDto signDto, HttpServletRequest request) {
        log.info("用户账号:{},用户密码:{}", signDto.getAccount(), signDto.getPassword());
        return userService.login(signDto, request);
    }

    @PostMapping("/logout")
    public R<Void> logout(@RequestParam Integer userId) {
        return userService.logout(userId);
    }

    @GetMapping("/get")
    public R<UserInfo> get(HttpServletRequest request) {
        // 获取token
        String token = request.getHeader("Authorization");
        token = token.replace("Bearer ", "");
        log.info("用户token-{}", token);
        Long id = null;
        try {
            id = JwtUtils.parseToken(token);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return userService.get(id);
    }

}
